package com.woniuxy.sender;

import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author: 曾令忠
 * @Description: 利用插件在发送消息时设置过期时间
 * @Date: 2020/7/7 0007-下午 2:34
 */
@Component
public class PluginSender {
    @Autowired
    RabbitTemplate rabbitTemplate;
    public void send(String msg,int delayTime){
        System.out.println("生产者发送消息："+new Date());
        //发送消息的同时设置过期时间
        rabbitTemplate.convertAndSend("customExchange", "dalay_key", msg, new MessagePostProcessor() {
            /**
             * 消息后置处理器，消息在打包好后rabbit会自动调用该方法，将消息作为参数传入
             * @param message
             * @return
             * @throws AmqpException
             */
            @Override
            public Message postProcessMessage(Message message) throws AmqpException {
                message.getMessageProperties().setDelay(delayTime);
                return message;
            }
        });
    }
}
